# video_ai_service.py

from fastapi import FastAPI, UploadFile, File, Form
from fastapi.responses import JSONResponse
import os
import tempfile
from dashscope import MultiModalConversation

# 初始化 FastAPI 应用
app = FastAPI(title="视频 AI 分析服务")

# DashScope API Key
DASHSCOPE_API_KEY = os.getenv("DASHSCOPE_API_KEY", "sk-3875f975f92949a79f522ab1bf9d2b40")

@app.post("/analyze_video/")
async def analyze_video_endpoint(
    video: UploadFile = File(...),
    fps: float = Form(2.0)  # 默认每秒抽 2 帧
):

    try:
        # 创建临时文件保存上传的视频
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(video.filename)[1]) as tmpfile:
            content = await video.read()
            tmpfile.write(content)
            temp_video_path = tmpfile.name

        # 构建消息体
        messages = [
            {
                "role": "user",
                "content": [
                    {"video": temp_video_path, "fps": fps},
                    {"text": "请分析这段视频在9分钟时段发生了什么？用中文回答。"},
                ],
            },
        ]

        # 调用 DashScope 模型
        response = MultiModalConversation.call(
            api_key=DASHSCOPE_API_KEY,
            model="qwen2.5-vl-72b-instruct",
            messages=messages,
        )

        # 提取 AI 回复的文本
        result_text = response["output"]["choices"][0]["message"]["content"][0]["text"]

        # 返回 JSON 响应
        return JSONResponse({
            "success": True,
            "analysis": result_text
        })

    except Exception as e:
        return JSONResponse({
            "success": False,
            "error": str(e)
        }, status_code=500)

    finally:
        # 删除临时文件
        if 'temp_video_path' in locals() and os.path.exists(temp_video_path):
            os.unlink(temp_video_path)

# 启动方式：
# uvicorn video_ai_service:app --reload --host 0.0.0.0 --port 8000



